﻿using Microsoft.AspNetCore.Mvc.Filters;
using PowerHub.MES.Jwt;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.Text;
using System.Threading.Tasks;

namespace PowerHub.MES.Common
{
    /// <summary>
    /// 全局获取用户信息
    /// </summary>
    public class AsyncSessionFilter : IAsyncActionFilter
    {
        private readonly UserServices _session;

        public AsyncSessionFilter(UserServices session)
        {
            _session = session;
        }

        public async Task OnActionExecutionAsync(
          ActionExecutingContext context,
          ActionExecutionDelegate next)
        {
            var user = context.HttpContext.User;
            var authorizationHeader = context.HttpContext.Request.Headers["Authorization"].ToString();

            if (!string.IsNullOrEmpty(user.FindFirst(c => c.Type == "userId")?.Value))
            {
                _session.UserId = user.FindFirst(c => c.Type == "userId")?.Value;
                _session.UserName = user.FindFirst(c => c.Type == "userName")?.Value;
                _session.Role = user.FindFirst(c => c.Type == ClaimTypes.Role)?.Value;
            }
            else if (!string.IsNullOrEmpty(authorizationHeader))
            {
                var users = JwtService.GetUserIdFromJwtToken(authorizationHeader.Replace("Bearer ", ""));
                _session.UserId = users.Uid;
                _session.Role = users.Role;
                _session.UserName = users.UserName;
            }

            await next();
        }
    }
}
